<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/21 0021
 * Time: 上午 10:27
 */

namespace Home\Model;
use Think\Model;

class HistoryModel extends Model{
    //更改或添加浏览历史
    public function set_history($userid,$wzno){
        //先判断有没有该条记录
        $where = "user_id='{$userid}' and wzno={$wzno}";
        $his_info = $this->field('id')->where($where)->find();
        if($his_info){ //有记录,更改时间
            $data['time'] = time();
            $this->where("id={$his_info['id']}")->save($data);
        }else{  //没记录,添加记录
            //取出该用户的浏览记录的总数
            $count = $this->where("user_id='{$userid}'")->count();
            if($count > 50){  //判断如果记录数大于50,就删除最小的一条记录
                $min_id = $this->query("select min(id) id from history where user_id='{$userid}'");
                $sql = "delete from history where id={$min_id[0]['id']}";
                $this->execute($sql);
            }
            $this->add(array(
                'user_id' => $userid,
                'wzno' => $wzno,
                'time' => time()
            ));
        }
    }

    public function search($userid){
        $info = D()->query("select b.wzno,b.wzmc,b.dhbs,c.flmc,d.qc from history a
                            left join b_c_wzbm b on a.wzno=b.wzno
                            left join b_c_wzfl c on b.wzfl=c.flno
                            left join b_p_gysjbqk d on b.gysno=d.gysno
                            where a.user_id='{$userid}'");
        foreach($info as $k=>&$v){
            $row = explode(' ',$v['dhbs']);
            $v['dhbs'] = array($row[0],$row[1],$row[2]);
        }

        return $info;
    }

}
